
const { Base_Client } = require('../../ws_frame/client/class/Base_Client.js');
const Response = require('./Response.js');


class Client extends Base_Client {
    constructor(ws, timeout = CONF.CONFIG.get('Websocket')?.['SendJsonTimeout'] ?? 3000){
        super(ws);
        this.timeout = timeout;
        this.onlineClientsInfo = {}, // 协调服务端在线客户端信息(实时更新)
        this.onlinePlayersInfo = {}; // 协调服务端在线玩家信息(实时更新)
        this.playerLoginSyncSuccess = {}; // 玩家登录同步是否完成
        this.apiListener = undefined; // api监听器
        this.syncLLMoneyStatus = new Set(); // llmoney同步缓存
    } 
 
    // sendJson(json){
    //     return this.ws.send(JSON.stringify(json));
    // }

    /**
     * @description: 发送请求
     * @param {object} json
     * @param {function} callback
     * @param {number} timeout
     * @return {*}
     */
    sendJson(json, successCallback, errorCallback, timeout = this.timeout){
        if (json instanceof Response){json = json.json;}
        if (successCallback instanceof Function || errorCallback instanceof Function){
            if (!json.header){json.header = {};}
            const requestId = json.header.requestId || utils.uuidv4();
            json.header.requestId = requestId;
            // 设置超时拒绝
            const timeoutId = setTimeout(() => {
                if (WSC.pendingRequests.has(requestId)) {
                    const request = WSC.pendingRequests.get(requestId);
                    request.errorCallback(`请求超时: ${request.json?.header?.url??''} ${requestId}`);
                    WSC.pendingRequests.delete(requestId);
                    clearTimeout(request.timeout);
                }
            }, timeout);
            // 存储请求上下文
            WSC.pendingRequests.set(requestId, { 
                json: json,
                successCallback: successCallback instanceof Function ? successCallback : ()=>{}, 
                errorCallback: errorCallback instanceof Function ? errorCallback : (errmsg)=>{
                    WSC.logger.warn(errmsg);
                }, 
                timeout: timeoutId 
            });
            if (CONF.CONFIG.get('Websocket')['Debug'] == true){
                console.log('客户端发送: ', json, '\n-----------------------\n ');
            }
            return this.send(JSON.stringify(json));
        }
        if (!successCallback && !errorCallback){
            if (CONF.CONFIG.get('Websocket')['Debug'] == true){
                console.log('客户端发送: ', json, '\n-----------------------\n ');
            }
            return this.send(JSON.stringify(json));
        }
        throw new Error('function sendJson: successCallback and errorCallback must be function');
    }

    /**
     * @description: 异步发送请求(不会被其他事件监听到)
     * @param {object} json - 要发送的JSON数据
     * @param {number} [timeout=] - 超时时间(毫秒)
     * @return {Promise} - 返回包含响应结果的Promise
     */
    sendJsonAsync(json, timeout = this.timeout){
        return new Promise((resolve, reject) => {
            this.sendJson(json, 
            (request, response) => {
                resolve({req: request, res: response});
                return false;
            },
            (err)=>{
                WSC.logger.warn(err);
                resolve({req: null, res: null});
            },
            timeout);
        });
    }

    /**
     * @description: 发送WSC服务端控制台消息
     * @param {string} msg 消息
     * @param {string} level 日志等级
     * @return {*}
     */    
    sendServerLogger(msg, level='info'){
        return this.sendJson(new Response()
        .setUrl('/bds/serverLogger')
        .setData({
            msg: msg + ` | ${CONF.CONFIG.get('Websocket')['ServerName']}`,
            level: level,
        }));
    }
}
module.exports = {
    Client
};

